$file1 = $ARGV[0];
chomp($file1);
$count = $ARGV[1];
chomp($count);
open(BUFF,"$file1");
#open(BUFF,"$file1");
open(BUF,"chr.txt");
while($line=<BUF>)
{
	chomp($line);
	#print $line."\n";
	@chrarr = split(" ",$line);
	chomp($chrarr[0]);
	$chr{$chrarr[0]} = $chrarr[2];
}
$outfile = $file1;
$outfile = "out_$outfile";
#print $outfile."\n";
open(WRBUFF,">$outfile");

$prevchr="";
$presentcount = 0;
$next = 0;
#$line = <BUFF>;
#print $line."\n";
while($line = <BUFF>)
{
	chomp($line);
	#print $line."\n";
	@array = split(/\t/,$line);
	#print @array."\n";
	#print $array[2]."\t".$array[3]."\n";
	$chr = $array[2];
	$pos = $array[3];
	$strand = $array[1];	
    if(exists($chr{$chr}))
    {
	$readcount = 1;
	

		if($chr ne $prevchr)
		{
			if($prevchr ne "")
			{
				#print "sucess\n";
				 $binname = $prevchr."_".$prev."_".$next;
				print WRBUFF $binname."\t".$presentcount."\n";
				#$prev = $prev+$count;
				#$next = $prev+$count-1;
				while($next < $end)
				{
					#$binname = $chr."_".$prev."_".$next;
					 #print WRBUFF $binname."\t"."0"."\n";
					$prev = $prev+$count;
					$next = $prev+$count-1;
					$binname = $prevchr."_".$prev."_".$next;
					print WRBUFF $binname."\t"."0"."\n";
				}
			}
			$start = 1;
			$end = $chr{$chr};
			$prev = $start;
			$next = $prev+$count-1;
			$presentcount = 0;
			#print "$pos\t$prev\t$next\n";			
			while($next  < $pos)
			{
				$binname = $chr."_".$prev."_".$next;
				print WRBUFF $binname."\t"."0"."\n";
				$prev = $prev+$count;
				$next = $prev+$count-1;
			}
			#print "$pos\t$prev\t$next\n";
			#die ;	
		}			
		if($pos > $next)
		{
			
			$binname = $chr."_".$prev."_".$next;
			print  WRBUFF  $binname."\t".$presentcount."\n";
			
			$prev = $prev+$count;
                        $next = $prev+$count-1;
			while($pos > $next)
			{
				$binname = $chr."_".$prev."_".$next;
                        	print  WRBUFF  $binname."\t"."0"."\n";
                        	$prev = $prev+$count;
                        	$next = $prev+$count-1;
			}
			$presentcount = $readcount;
		}
	
		elsif($pos >= $prev && $pos <= $next)
		{
			$presentcount = $presentcount+$readcount;
		}	
		else
		{
		}
	$prevchr = $chr;
	$prevpos = $pos;
     }	
}
$chr = $prevchr;
if(exists($chr{$chr}))
{
	$binname = $chr."_".$prev."_".$next;
	print WRBUFF $binname."\t".$presentcount."\n";
 #$prev = $prev+$count;
 #$next = $prev+$count-1;

#print "success $prev $next $end\n";
	while($next <= $end)
	{
	#$binname = $chr."_".$prev."_".$next;
	 #print WRBUFF $binname."\t"."0"."\n";
		$prev = $prev+$count;
        	$next = $prev+$count-1;
       		$binname = $chr."_".$prev."_".$next;
        	print WRBUFF $binname."\t"."0"."\n";
	}
}
